package com.retch.wenchengmao.recodeauthutils.httpUrlConnection;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.retch.wenchengmao.recodeauthutils.R;

import org.json.JSONObject;

/**
 * author:wenchengmao
 * time:  2017/3/29.
 * email: wenchengmao@yeah.net
 */

public class HttpUrlConnectionActivity extends AppCompatActivity {
    private TextView data;
    public static final int SUCCESS=1;
    public static final int FAIL=0;
    private EditText email,password;
    private Button login;
    Handler handler=null;
    String datas;
    public void onCreate(Bundle savesInstanceState)
    {
        super.onCreate(savesInstanceState);
        setContentView(R.layout.activity_http_url_connection);
        initView();
    }
    public void initView()
    {
        email=(EditText)findViewById(R.id.email);
        password=(EditText)findViewById(R.id.password);
        login=(Button)findViewById(R.id.login);
        data=(TextView)findViewById(R.id.data);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //子线程处理网络请求
                if(email.getText().toString().equals("")||password.getText().toString().equals(""))
                {
                    Toast.makeText(HttpUrlConnectionActivity.this,"info is not full",Toast.LENGTH_LONG).show();
                }
                else
                {
                    childHandler();
                    handler();
                }

            }
        });
    }

    public void childHandler()
    {
        new Thread(new Runnable() {

            @Override
            public void run() {
                Message message=new Message();
                datas= HttpUrlConnectionUtils.loginByPost(email.getText().toString(),password.getText().toString());
                if(datas!=null)
                {
                    message.what=SUCCESS;
                }
                else message.what=FAIL;
                handler.sendMessage(message);
            }

        }).start();

    }

    public void handler()
    {
        handler=new Handler()
        {
            @Override
            public void handleMessage(Message message){
                if(message.what==SUCCESS)
                {
                    data.setText(datas);
                    try {
                        JSONObject jsonObject=new JSONObject(datas);
                        Log.d("name",jsonObject.getString("username"));
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        };
    }

}
